<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

    <link rel="stylesheet" href="../bootstarp/css/bootstrap.min.css" />
    <link rel="stylesheet" href="../css/car.css" />
    <script src="./Ajax.js"></script>
    <script src="./获得Cookie方法.js"></script>
</head>

<body>
    <h1>我是购物车页面</h1>
    <div class="container">
        <div class="panel panel-default">
            <div class="panel-heading">
                <div class="content">
                    <label for="" class="checkbox">
                        <input type="checkbox" id='allcheck' />
                        <span>全选</span>
                    </label>
                    <label for="" class="type">
                        <span>商品种类：</span>
                        <span id='total'>0</span>
                    </label>
                    <label for="" class="qty">
                        <span>所选商品数量：</span>
                        <span id='totalnum'>0</span>
                    </label>
                    <label for="" class="price">
                        <span>所选商品价格：</span>
                        <span id='totalprice'>0</span>
                    </label>
                    <label for="">
                        <button class="btn btn-warning btn-xs settlement">结算</button>
                        <button class="btn btn-info btn-xs empty">
                            清空购物车
                        </button>
                    </label>
                </div>
            </div>
            <div class="panel-body">
                <ul>
                    <!-- <li>
                        <div class="media">
                            <div class="media-left media-middle">
                                <input type="checkbox">
                                <a href="#">
                                    <img class="media-object"
                                        src="https://image4.suning.cn/uimg/b2c/newcatentries/0070081143-000000000131021736_2_200x200.jpg"
                                        alt="">
                                </a>
                            </div>
                            <div class="media-body">
                                <h4 class="media-heading">诗绪刺绣改良旗袍连衣裙女夏装2020年新款中国风印花A字裙子52150</h4>
                                <div class="price">
                                    <i class="glyphicon glyphicon-yen"></i>
                                    <span>199.8</span>
                                </div>
                                <div class="btn">
                                    <p>
                                        <butto class="btn btn-danger">删除商品</butto>
                                    </p>
                                    <div class="btn-group" role="group" aria-label="...">
                                        <button class="btn btn-default">-</button>
                                        <button class="btn btn-default">1</button>
                                        <button class="btn btn-default">+</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </li> -->
                </ul>
            </div>
        </div>
    </div>
    <script>
        let login = getCookie('login');
        if (!login) {
            localStorage.setItem('url', location.href);
            location.href = './6.5login.htm';
        }
        class Car {
            constructor(ele, username) {
                this.ele = document.querySelector(ele);
                this.username = username;
                this.init();

            }
            init() {
                this.ul = this.ele.querySelector('ul');
                this.total = this.ele.querySelector('#total');
                this.allcheck = this.ele.querySelector('#allcheck');
                this.totalnum = this.ele.querySelector('#totalnum');
                this.totalprice = this.ele.querySelector('#totalprice');
                this.getDate();

                this.ele.onclick = (e) => {
                    // 全选
                    if (e.target.id == 'allcheck') {
                        let data = JSON.parse(localStorage.getItem('data'));
                        data = data.map(item => {
                            e.target.checked ? item.is_select = "1" : item.is_select = "0";
                            return item;
                        });
                        localStorage.setItem('data', JSON.stringify(data));
                        this.Runder();
                        return;
                    }
                    // 单选
                    if (e.target.className == 'check') {
                        let data = JSON.parse(localStorage.getItem('data'));
                        // 获得商品id
                        let id = e.target.getAttribute('idx');
                        data.forEach(item => {
                            if (item.goods_id == id) {
                                // 如果被勾选 则 值为1 
                                e.target.checked ? item.is_select = "1" : item.is_select = "0";
                            }

                        });
                        let flag = data.every(item => {
                            // 全部单选都被选上的时候 flag才为true
                            return item.is_select == "1";
                        });
                        this.allcheck.checked = flag;

                        localStorage.setItem('data', JSON.stringify(data));
                        this.Runder();
                        return;
                    }
                    // 删除商品
                    // classList.contains 在className中查找是否有 del 这个className
                    if (e.target.classList.contains('del')) {
                        let id = e.target.getAttribute('idx');
                        let flag = confirm('是否删除该商品');
                        flag ? this.remove(id) : '';
                        return;
                    }

                    // 结算商品
                    if (e.target.classList.contains('settlement')) {
                        let data = JSON.parse(localStorage.getItem('data'));
                        data.forEach((item) => {
                            if (item.is_select == '1') {
                                // console.log(item.goods_id);
                                this.remove(item.goods_id);
                            }
                        });
                        return;
                    }

                    // 清空购物车
                    if (e.target.classList.contains('empty')) {
                        let flag = confirm('确定要清空购物车吗？');
                        if (flag) {
                            pAjax({
                                url: '../6.6ClearData.php',
                                data: {
                                    username: this.username,
                                },
                            }).then(res => {
                                res = JSON.parse(res);
                                if (res.code) {
                                    localStorage.setItem('data', JSON.stringify([]));
                                    this.Runder();
                                }
                            });
                        }
                        return;
                    }

                    // 按钮+
                    if(e.target.classList.contains('add')){
                        let num = e.target.previousElementSibling.innerText * 1;
                        let id  = e.target.getAttribute('data_id');
                        num++;
                        this.updata(id,num);
                        return ;
                    }

                    // 按钮-
                    if(e.target.classList.contains('cut')){
                        let num = e.target.nextElementSibling.innerText * 1;
                        let id  = e.target.getAttribute('data_id');
                        num--;
                        this.updata(id,num);
                        return ;
                    }
                }


            }

            async remove(id) {
                let data = JSON.parse(localStorage.getItem('data'));
                let p = await pAjax({
                    url: '../6.4removeCar.php',
                    data: {
                        username: this.username,
                        goods_id: id,

                    }
                });
                p = JSON.parse(p);
                if (p.code) {
                    data = data.filter(item => {
                        return item.goods_id != id;
                    });
                    localStorage.setItem('data', JSON.stringify(data));
                    this.Runder();

                }


            }


            // 数量的+ - 更新
            updata(id,num){
                pAjax({
                    url:'../6.7Updata.php',
                    data:{
                        username:this.username,
                        goods_id:id,
                        goods_num:num,
                    }
                }).then(res=>{
                    res = JSON.parse(res);
                    if(res.code){
                        this.data.forEach(item=>{
                            item.cart_number = item.goods_id == id ? num : item.cart_number;
                        });
                        localStorage.setItem('data',JSON.stringify(this.data));
                        this.Runder();
                    }
                });
            }

            async getDate() {
                let p = await pAjax({
                    url: '../6.3getCar.php',
                    data: {
                        username: this.username,
                    }
                });
                // 把获得的数据放在localStorage中的data中
                // 这样会方便操作，不用每次都去到数据库里面操作
                localStorage.setItem('data', p);
                this.Runder();
            }
            Runder() {
                //从localStorage中拿到的是Json类型，所以需要转为js类型
                this.data = JSON.parse(localStorage.getItem('data'));
                console.log(this.data);
                this.getNum();
                this.total.innerHTML = this.data.length;
                if (this.data.length == 0) {
                    this.ul.innerHTML = ` 
                    <div class="jumbotron">
                        <h1>您暂时还你没有数据，请到列表页选购</h1>
                        <p>
                            <a class="btn btn-primary btn-lg" href="./6.2datils.html" role="button">跳转列表页</a>
                            </p>
                    </div>`;
                    return;
                }
                let str = '';
                this.data.forEach(item => {
                    str += `
                    <li>
                        <div class="media">
                            <div class="media-left media-middle">
                                <input type="checkbox" idx='${item.goods_id}' ${item.is_select=="1"? "checked":""}  class="check">
                                <a href="#">
                                    <img class="media-object"
                                        src="${item.goods_small_logo}"
                                        alt="">
                                </a>
                            </div>
                            <div class="media-body">
                                <h4 class="media-heading">${item.goods_name}</h4>
                                <div class="price">
                                    <i class="glyphicon glyphicon-yen"></i>
                                    <span>${item.goods_price}</span>
                                </div>
                                <div class="btn">
                                    <p>
                                        <butto class="btn btn-danger del" idx=${item.goods_id} >删除商品</butto>
                                    </p>
                                    <div class="btn-group" role="group" aria-label="...">
                                        <button class="btn btn-default cut" data_id=${item.goods_id} ${item.cart_number=='1' ? 'disabled':''}>-</button>
                                        <button class="btn btn-default">${item.cart_number}</button>
                                        <button class="btn btn-default add" data_id=${item.goods_id}>+</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </li> 
                    `;
                });
                this.ul.innerHTML = str;
            }

            // 计算商品数量和总价格
            getNum() {
                let numdata = this.data.filter(item => {
                    return item.is_select == '1';
                });
                this.totalnum.innerText = numdata.reduce((pre, item) => {
                    return pre + item.cart_number * 1;
                }, 0);

                this.totalprice.innerHTML = numdata.reduce((pre, item) => {
                    return pre + item.cart_number * item.goods_price;
                }, 0).toFixed(2);

            }
        }

        new Car('.container', login);
    </script>
</body>

</html>